const mch_id = "1584325341" //换成你的商户号

const cloud = require('wx-server-sdk')
const envId = "daanquanyou-rlnyt"
cloud.init({
  env:envId
})
const db =cloud.database()

exports.main = async(event,context) =>{
  const wxContext = cloud.getWXContext()
  let openid = wxContext.OPENID

  let { 
    totalFee, 
     key,
  } = event

  let body = event.body //商品的描述
  let nonceStr = Math.random().toString(36).substr(2,13)  //32位以内随机字符串，这里是11位
  let timeStamp = parseInt(Date.now() / 1000)
  let outTradeNo = "test" + timeStamp + nonceStr  //商户订单号，32位以内，这里是25位
  let tradeType = "JSAPI"   //交易类型，小程序下JSAPI

  // 生成预支付交易单
  const result = await cloud.cloudPay.unifiedOrder({
    body,                 //商品的描述
    nonceStr,             //32位以内随机字符串，这里是11位
    tradeType,            //交易类型，小程序下JSAPI
    outTradeNo,           //商户订单号，32位以内，这里是25位
    spbillCreateIp:"127.0.0.1",    
    subMchId: mch_id,  //商户号
    totalFee : 1,      //订单金额
    envId:envId ,      //环境
    functionName: "recpay",     //接受微信支付异步通知回调的云函数名
  })

  // 记录预支付交易单信息
 await db.collection('order').add({
    data:{
      _openid:openid,
      body,
      outTradeNo,
      totalFee,
      status:0,
      createTime:Date.now(),
      key:key
    }
  })
  .then(res => {
    console.log(res)
  })
  .catch(console.error)

  return result
}


